package com.example.capsule_chat0322.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.adapter.FriendListAdapter;
import com.example.capsule_chat0322.adapter.MsgAdapter;
import com.example.capsule_chat0322.bean.GlobalRoomBean;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.Msg;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.ActionType;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalChatRoomMap;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.netty.NettyClient;
import com.example.capsule_chat0322.request.MessagesRequest;
import com.example.capsule_chat0322.request.UserInfoRequest;
import com.example.capsule_chat0322.utils.AlterUtils;
import com.example.capsule_chat0322.utils.FileUtils;
import com.example.capsule_chat0322.utils.ThumbnailUtil;
import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * @Author zhuzhiming
 * @Date 2022/4/30 20:58
 */
public class OneToOneChatActivity extends AppCompatActivity {

    private List<Msg> msgList = new ArrayList<>();
    private Button send;
    private ImageView send_file;
    private EditText inputText;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;
    private NettyClient nettyClient;
    private String friendName;
    private String roomName;
    private ImageView tv_back;
    private String friendId;
    private String myId;
    private String filePath;
    private TextView username;
    private TextView more_function;


    private static int ALBUM_RESULT_CODE = 0x999;
    private final int USER_INFO_CODE = 0;
    private static final int UPDATE_INFO_CODE = 2;

    private boolean isOver = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one_to_one_chat_room);
        initView();//初始化UI控件
    }

    @SuppressLint("SetTextI18n")
    private void initView() {

        if (ActivityCompat.checkSelfPermission(OneToOneChatActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(OneToOneChatActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        // right_msg = findViewById(R.id.right_msg);
        send_file = findViewById(R.id.send_file);
        tv_back = findViewById(R.id.tv_back);
        msgRecyclerView = findViewById(R.id.msg_recycler_view01);
        username = findViewById(R.id.room_name);
        more_function = findViewById(R.id.more_function);
        Intent intent = getIntent();
        friendName = intent.getStringExtra("friendName");
        friendId = String.valueOf(intent.getIntExtra("friendId", 0));
        myId = (String) GlobalAssistMap.getObject("userId");


        if (myId == null) {
            try {
                Thread.sleep(100);
                myId = (String) GlobalAssistMap.getObject("userId");
                if (myId == null) {
                    Thread.sleep(200);
                    myId = (String) GlobalAssistMap.getObject("userId");
                    if (myId == null) {
                        Thread.sleep(500);
                        myId = (String) GlobalAssistMap.getObject("userId");
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (myId == null) return;

        roomName = (Integer.parseInt(myId) + Integer.parseInt(friendId)) + "chatroom";

        String onlineStatus = intent.getIntExtra("onlineStatus", 0) == 0 ? "离线" : "在线";

        username.setText(friendName + "(" + onlineStatus + ")");

        initMessageListView();

        this.nettyClient = NettyClient.getInstance();


        msgRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == 0) {
                    adapter.setScrolling(false);
                    adapter.notifyDataSetChanged();
                } else {
                    adapter.setScrolling(true);

                }

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        send_file.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openSysAlbum();
                // pickFile(view);
            }
        });


        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


//
//        more_function.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
//            @Override
//            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
//                contextMenu.add(0, 1, 0, "复制文字");
//                contextMenu.add(0, 2, 0, "粘贴文字");
//                contextMenu.add(0, 3, 0, "全选文字");
//            }
//        });


    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    //ContextMenu菜单选项的选项选择的回调事件
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        //参数为用户选择的菜单选项对象
        //根据菜单选项的id来执行相应的功能
        switch (item.getItemId()) {
            case 1:
                Msg msg = (Msg) GlobalAssistMap.getObject("selectMsg");
                inputText.setText(msg.getContent());
                inputText.setTextColor(Color.parseColor("#ff0000"));
                GlobalAssistMap.removeObject("selectMsg");
                break;
            case 2:
                Toast.makeText(this, "粘贴文字", Toast.LENGTH_SHORT).show();

                break;
            case 3:
                Toast.makeText(this, "全选文字", Toast.LENGTH_SHORT).show();

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                inputText.setTextColor(Color.parseColor("#FF000000"));
                sendMessage(content);
            }
        });

        inputText.setOnKeyListener(new EditText.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                boolean flag = false;
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    String content = inputText.getText().toString();
                    sendMessage(content);
                    flag = true;
                }
                return flag;
            }
        });

    }


    public void sendMessage(String content) {


        if (!"".equals(content)) {
            //如果字符串不为空，则创建Msg对象
            MessageBean messageBean = new MessageBean();
            messageBean.setOneToOne(true);
            messageBean.setSenderId(myId);
            messageBean.setContent(content);
            messageBean.setRoomName(roomName);
            messageBean.setMsgType(0);
            messageBean.setReceiverId(friendId);
            messageBean.setField(GlobalAssistMap.getObject("field").toString());
            messageBean.setActionType(ActionType.CHAT_TYPE);
            Date date = new Date();
            @SuppressLint("SimpleDateFormat") String dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            messageBean.setSendTime(dateFormat);
            final UserInfoBean[] userInfoBean = {(UserInfoBean) GlobalAssistMap.getObject("userInfo")};
            if (userInfoBean[0] == null) {

                UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(@NonNull Message message) {
                        userInfoBean[0] = (UserInfoBean) message.obj;
                        if (userInfoBean[0] != null) {
                            GlobalAssistMap.putObject("userInfo", userInfoBean[0]);
                        }
                        return true;
                    }
                }), GlobalAssistMap.getObject("userId").toString());
            }

            while (userInfoBean[0] == null) {
                try {
                    Thread.sleep(50);
                    if (userInfoBean[0] == null) {
                        Thread.sleep(100);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            }
            messageBean.setSenderName(userInfoBean[0].getNickname());
            messageBean.setSenderAvatarPath(userInfoBean[0].getAvatarUrl());
            Integer msgId = (Integer) GlobalAssistMap.getObject("globalMsgId");
            if (msgId == null) {
                GlobalAssistMap.putObject("globalMsgId", 1);
                msgId = 1;
            }

            messageBean.setLocalMsdId(msgId);

            nettyClient.sendMessage(messageBean);
            Msg sendMsg = new Msg(String.valueOf(userInfoBean[0].getId()), roomName, Msg.WORD_TYPE, content, Msg.TYPE_SEND, userInfoBean[0].getAvatarUrl(), true);

            GlobalAssistMap.putObject(msgId + "msg", sendMsg);

            updateRoomMessages(sendMsg);
            inputText.setText("");//清空输入框的内容
            //inputText.requestFocus();//输入光标回到输入框中
        }
    }

    @SuppressLint("NewApi")
    public void initMessageListView() {

        GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(roomName);

        LinearLayoutManager layoutManager = new LinearLayoutManager(OneToOneChatActivity.this);

        if (globalRoomBean != null) {

            CompletableFuture.runAsync(()->{
                MessagesRequest.updateMessageStatus(roomName);
            });

            this.adapter = globalRoomBean.getAdapter();
            this.msgList = globalRoomBean.getMsgList();
            this.msgRecyclerView.setLayoutManager(layoutManager);
            if (GlobalAssistMap.getObject("avatarUpdate") != null) {
                UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
                for (Msg msg : msgList) {
                    if (msg.getType() == Msg.TYPE_SEND) {
                        msg.setAvatarPath(userInfoBean.getAvatarUrl());
                    }
                }
            }
            List<Msg> msgArrayList = new ArrayList<>();
            for (Msg msg : msgList) {
                if (!msg.getAvatarPath().equals("")) {
                    msgArrayList.add(msg);
                }
            }
            msgList = msgArrayList;
            adapter = new MsgAdapter(msgList);
            this.msgRecyclerView.setAdapter(adapter);
            this.adapter.notifyItemInserted(this.msgList.size() > 0 ? this.msgList.size() - 1 : 0);//当有新消息是刷新RecyclerView中的显示
            this.msgRecyclerView.scrollToPosition(this.msgList.size() > 0 ? this.msgList.size() - 1 : 0);//将RecyclerView定位在最后一行

            globalRoomBean.setRoomName(roomName);
            globalRoomBean.setActivity(OneToOneChatActivity.this);
            globalRoomBean.setMsgRecyclerView(msgRecyclerView);
            globalRoomBean.setMsgList(msgList);
            globalRoomBean.setAdapter(adapter);
            GlobalChatRoomMap.putRoomInfo(roomName, globalRoomBean);
        } else {

            Handler handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message message) {
                    msgList = (List<Msg>) message.obj;
                    adapter = new MsgAdapter(msgList);
                    msgRecyclerView.setLayoutManager(layoutManager);
                    msgRecyclerView.setAdapter(adapter);
                    adapter.notifyItemInserted(msgList.size() > 0 ? msgList.size() - 1 : 0);//当有新消息是刷新RecyclerView中的显示
                    msgRecyclerView.scrollToPosition(msgList.size() > 0 ? msgList.size() - 1 : 0);//将RecyclerView定位在最后一行
                    GlobalRoomBean globalRoomBean = new GlobalRoomBean();
                    globalRoomBean.setRoomName(roomName);
                    globalRoomBean.setActivity(OneToOneChatActivity.this);
                    globalRoomBean.setMsgRecyclerView(msgRecyclerView);
                    globalRoomBean.setMsgList(msgList);
                    globalRoomBean.setAdapter(adapter);
                    GlobalChatRoomMap.putRoomInfo(roomName, globalRoomBean);
                    return true;
                }
            });

            MessagesRequest.getOneToOneMessages(handler, roomName);
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {

            if (resultCode == USER_INFO_CODE) {
                String senderId = "";
                String avatarPath = null;
                String sign = null;
                String avatarUpdate = data.getStringExtra("avatarUpdate");
                String signUpdate = data.getStringExtra("signUpdate");
                if (avatarUpdate != null) {
                    if (avatarUpdate.contains("|")) {
                        senderId = avatarUpdate.substring(0, avatarUpdate.indexOf("|"));
                        avatarPath = avatarUpdate.substring(avatarUpdate.indexOf("|") + 1);
                    } else {
                        senderId = avatarUpdate.substring(0, avatarUpdate.indexOf("/"));
                        avatarPath = avatarUpdate.substring(avatarUpdate.indexOf("/"));
                    }
                }
                if (signUpdate != null) {
                    senderId = signUpdate;
                }
                updateMessageList(senderId, avatarPath);
            } else if (resultCode == UPDATE_INFO_CODE) {

            } else {
                handleImageOnKitKat(data);
            }
        }
    }


    private void openSysAlbum() {

        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "file/*");
        startActivityForResult(albumIntent, ALBUM_RESULT_CODE);

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void handleImageOnKitKat(Intent data) {


        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {

            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);

            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];

                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;

                filePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {

                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.parseLong(docId));

                filePath = getImagePath(contentUri, null);

            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // 如果是content类型的Uri，则使用普通方式处理
            filePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {

            // 如果是file类型的Uri，直接获取图片路径即可
            filePath = uri.getPath();
        }

        // 根据图片路径显示图片
        try {
            if (filePath.endsWith(".jpeg") || filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".bmp") || filePath.endsWith("svg")) {
                displayImage(filePath);
            } else if (filePath.endsWith(".txt") || filePath.endsWith(".docx") || filePath.endsWith(".mp3") || filePath.endsWith(".apk") || filePath.endsWith(".pdf") || filePath.endsWith(".xlsx") || filePath.endsWith(".xls")) {
                displayFile(filePath);
            } else if (filePath.endsWith(".mp4")) {
                displayVideo(filePath);
            } else {
                AlterUtils.alertByToastInMainThread(this, "暂不支持该文件类型传输~");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取图片的路径
     */

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {

        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                try {
                    path = FileUtils.getPath(OneToOneChatActivity.this, uri);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
            cursor.close();
        }

        return path;
    }

    /**
     * 展示图片
     */

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void displayImage(String imagePath) throws FileNotFoundException {

        UserInfoBean userInfo = (UserInfoBean) GlobalAssistMap.getObject("userInfo");

        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
        Bitmap bitmap = (Bitmap) lruCache.get(imagePath.substring(imagePath.lastIndexOf("/")));
        //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(imagePath.substring(imagePath.lastIndexOf("/")));
        if (bitmap == null) {
            bitmap = BitmapFactory.decodeFile(imagePath);
            GlobalAssistMap.putObject(imagePath.substring(imagePath.lastIndexOf("/")), bitmap);
        }

        Integer msgId = (Integer) GlobalAssistMap.getObject("globalMsgId");
        if (msgId == null) {
            GlobalAssistMap.putObject("globalMsgId", 1);
            msgId = 1;
        }

        Msg sendMsg = new Msg(String.valueOf(userInfo.getId()), Msg.TYPE_SEND, Msg.Other_FILE_TYPE, imagePath, roomName, userInfo.getAvatarUrl(), null, true);

        GlobalAssistMap.putObject(msgId + "msg", sendMsg);

        updateRoomMessages(sendMsg);

        Integer finalMsgId = msgId;
        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                byte[] data = null;

                try {
                    FileInputStream inputStream = new FileInputStream(imagePath);
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                    data = new byte[inputStream.available()];
                    bufferedInputStream.read(data);
                    bufferedInputStream.close();
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                byte[] encode = new byte[0];
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    encode = Base64.getEncoder().encode(data);
                }

                String bytes = new String(encode);

                MessageBean messageBean = new MessageBean();
                messageBean.setSenderId(GlobalAssistMap.getObject("userId").toString());
                messageBean.setContent(bytes);
                messageBean.setImei((String) GlobalAssistMap.getObject("imei"));
                messageBean.setOneToOne(true);
                messageBean.setReceiverId(friendId);
                messageBean.setRoomName(roomName);
                messageBean.setFilePath(imagePath);
                messageBean.setFileName(imagePath.substring(imagePath.lastIndexOf("/") + 1));
                messageBean.setMsgType(1);
                messageBean.setLocalMsdId(finalMsgId);
                messageBean.setActionType(1);
                Date date = new Date();
                @SuppressLint("SimpleDateFormat") String dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                messageBean.setSendTime(dateFormat);
                UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
                messageBean.setSenderAvatarPath(userInfoBean.getAvatarUrl());
                messageBean.setSenderName(userInfoBean.getNickname());
                messageBean.setField(GlobalAssistMap.getObject("field").toString());

                GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        MessagesRequest.upLoadImage(new Gson().toJson(messageBean));
                    }
                });


            }
        });


    }


    @SuppressLint("DefaultLocale")
    private void displayFile(String filePath) throws IOException {

        UserInfoBean userInfo = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
        File file = new File(filePath);
        double fileSize = file.length();
        String suf = "";
        if (fileSize < 1024) {

            suf = String.format("%.1f", fileSize) + "B";
        } else if (fileSize > 1024 && fileSize < 1024 * 1024) {
            fileSize /= 1024;
            suf = String.format("%.1f", fileSize) + "Kb";
        } else if (fileSize > 1024 * 1024 && fileSize < 1024 * 1024 * 16) {
            fileSize /= 1024 * 1024;
            suf = String.format("%.1f", fileSize) + "Mb";
        } else if (fileSize >= 1024 * 1024 * 16) {
            return;
        }

        Integer msgId = (Integer) GlobalAssistMap.getObject("globalMsgId");
        if (msgId == null) {
            GlobalAssistMap.putObject("globalMsgId", 1);
            msgId = 1;
        }

        String finalSuf = suf;
        Integer finalMsgId = msgId;
        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                FileInputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                    byte[] bytes = new byte[inputStream.available()];
                    bufferedInputStream.read(bytes);
                    bufferedInputStream.close();
                    inputStream.close();
                    byte[] encode = new byte[0];
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        encode = Base64.getEncoder().encode(bytes);
                    }

                    String fileStr = new String(encode);
                    MessageBean messageBean = new MessageBean();
                    messageBean.setSenderId(GlobalAssistMap.getObject("userId").toString());
                    messageBean.setContent(fileStr);
                    messageBean.setImei((String) GlobalAssistMap.getObject("imei"));
                    messageBean.setOneToOne(true);
                    messageBean.setFilePath(filePath);
                    messageBean.setFileName(filePath.substring(filePath.lastIndexOf("/") + 1));
                    messageBean.setMsgType(2);
                    messageBean.setReceiverId(friendId);
                    messageBean.setRoomName(roomName);
                    messageBean.setActionType(1);
                    messageBean.setLocalMsdId(finalMsgId);
                    messageBean.setFileSize(finalSuf);
                    Date date = new Date();
                    @SuppressLint("SimpleDateFormat") String dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                    messageBean.setSendTime(dateFormat);
                    messageBean.setSenderAvatarPath(userInfo.getAvatarUrl());
                    messageBean.setSenderName(userInfo.getNickname());
                    messageBean.setField(GlobalAssistMap.getObject("field").toString());

                    GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            MessagesRequest.upLoadImage(new Gson().toJson(messageBean));
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });


        Msg sendMsg = new Msg(String.valueOf(userInfo.getId()), Msg.TYPE_SEND, Msg.Other_FILE_TYPE, filePath, roomName, userInfo.getAvatarUrl(), filePath.substring(filePath.lastIndexOf("/") + 1) + "  " + suf, true);

        GlobalAssistMap.putObject(msgId + "msg", sendMsg);

        updateRoomMessages(sendMsg);
    }


    private void displayVideo(String filePath) {

        UserInfoBean userInfo = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > 20971520) {
            AlterUtils.alertByToastInMainThread(OneToOneChatActivity.this, "上传视频不能大于20m");
            return;
        }
        String sizeSuffix = fileSize < 1024 ? fileSize + "B" : (fileSize < 1024 * 1024 ? fileSize + "Kb" : fileSize + "Mb");
        Bitmap videoThumbBitmap = ThumbnailUtil.getVideoThumb(filePath, MediaStore.Images.Thumbnails.MINI_KIND);

        Integer msgId = (Integer) GlobalAssistMap.getObject("globalMsgId");
        if (msgId == null) {
            GlobalAssistMap.putObject("globalMsgId", 1);
            msgId = 1;
        }

        Integer finalMsgId = msgId;
        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                FileInputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                    byte[] bytes = new byte[inputStream.available()];
                    bufferedInputStream.read(bytes);
                    bufferedInputStream.close();
                    inputStream.close();
                    byte[] encode = new byte[0];
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        encode = Base64.getEncoder().encode(bytes);
                    }

                    String fileStr = new String(encode);
                    MessageBean messageBean = new MessageBean();
                    messageBean.setSenderId(GlobalAssistMap.getObject("userId").toString());
                    messageBean.setContent(fileStr);
                    messageBean.setImei((String) GlobalAssistMap.getObject("imei"));
                    messageBean.setOneToOne(true);
                    messageBean.setRoomName(roomName);
                    messageBean.setReceiverId(friendId);
                    messageBean.setLocalMsdId(finalMsgId);
                    messageBean.setFilePath(filePath);
                    messageBean.setFileName(filePath.substring(filePath.lastIndexOf("/") + 1));
                    messageBean.setFileSize(sizeSuffix);
                    messageBean.setSenderName(userInfo.getNickname());
                    messageBean.setField(GlobalAssistMap.getObject("field").toString());
                    Date date = new Date();
                    @SuppressLint("SimpleDateFormat") String dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                    messageBean.setSendTime(dateFormat);
                    messageBean.setSenderAvatarPath(userInfo.getAvatarUrl());

                    GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            MessagesRequest.upLoadVideo(messageBean, videoThumbBitmap);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });


        String cacheKey = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf(".")) + ".jpeg";
        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
        lruCache.put(cacheKey, videoThumbBitmap);
        //GlobalAssistMap.putObject(cacheKey, videoThumbBitmap);


        Msg sendMsg = new Msg(String.valueOf(userInfo.getId()), Msg.TYPE_SEND, Msg.Other_FILE_TYPE, filePath, roomName, userInfo.getAvatarUrl(), ".mp4 ", true);

        GlobalAssistMap.putObject(msgId + "msg", sendMsg);


        updateRoomMessages(sendMsg);

    }

    private void updateRoomMessages(Msg sendMsg) {
        msgList.add(sendMsg);
        this.adapter = new MsgAdapter(msgList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(OneToOneChatActivity.this);
        msgRecyclerView.setLayoutManager(layoutManager);
        this.msgRecyclerView.setAdapter(adapter);
        adapter.notifyItemInserted(msgList.size() - 1);//当有新消息是刷新RecyclerView中的显示
        msgRecyclerView.scrollToPosition(msgList.size() - 1);//将RecyclerView定位在最后一行
        GlobalRoomBean globalRoomBean = new GlobalRoomBean();
        globalRoomBean.setAdapter(adapter);
        globalRoomBean.setRoomName(roomName);
        globalRoomBean.setMsgList(msgList);
        globalRoomBean.setActivity(OneToOneChatActivity.this);
        globalRoomBean.setMsgRecyclerView(msgRecyclerView);
        GlobalChatRoomMap.putRoomInfo(this.roomName, globalRoomBean);
    }


    public void showImage(String filePath) {

        Intent intent = new Intent();
        intent.putExtra("filePath", filePath);
        intent.setClass(OneToOneChatActivity.this, ShowImageActivity.class);
        startActivity(intent);

    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onDestroy() {
        super.onDestroy();

        CompletableFuture.runAsync(this::deleteFiles);

        MessageBean messageBean = new MessageBean();
        messageBean.setActionType(ActionType.CHAT_TYPE);
        UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
        messageBean.setSenderName(userInfoBean.getNickname());
        messageBean.setContent("人数减一");
        messageBean.setSenderId(GlobalAssistMap.getObject("userId").toString());
        messageBean.setMsgType(7);
        messageBean.setOneToOne(true);
        messageBean.setRoomName(roomName);
        messageBean.setPeopleChangeCount(-1);
        nettyClient.sendMessage(messageBean);

        String position = (String) GlobalAssistMap.getObject(friendId + "position");
        RecyclerView friend_recycler_view = (RecyclerView) GlobalAssistMap.getObject("friendRecyclerView");
        View view = friend_recycler_view.getChildAt(Integer.parseInt(position));
        FriendListAdapter adapter = (FriendListAdapter) GlobalAssistMap.getObject("friendListAdapter");

        adapter.deleteUnSignDot(view);

        if (msgList.size() > 0) {

            Msg msg = msgList.get(msgList.size() - 1);
            String content = "";
            if (msg.getFileType() == Msg.WORD_TYPE && msg.getContent() != null && msg.getType() != Msg.TYPE_REMIND) {
                content = msg.getContent().length() > 10 ? msg.getContent().substring(0, 10) + "..." : msg.getContent();
            } else if (msg.getFileType() == Msg.Other_FILE_TYPE) {
                if (msg.getFileDesc() == null) {
                    content = "[图片]";
                } else {
                    if (msg.getFileDesc().contains(".mp4 ")) {
                        content = "[视频]";
                    } else {
                        content = "[文件]";
                    }
                }
            } else if (msg.getFileType() == Msg.RECALL_TYPE || msg.getType() == Msg.TYPE_REMIND) {
                if (msg.getSenderId().equals(friendId)) {
                    content = "对方撤回了一条消息";
                } else {
                    content = "您撤回了一条消息";
                }
            }
            adapter.updateLastMessageView(view, friendId, content, false,false);

        }


    }


    public void deleteFiles() {
        Set<File> fileSet = (Set<File>) GlobalAssistMap.getObject("fileSet");
        if (fileSet.size() > 0) {
            GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        Iterator<File> iterator = fileSet.iterator();
                        while (iterator.hasNext()) {
                            File file = iterator.next();
                            if (file.exists()) {
                                try {
                                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                                    bufferedOutputStream.write(new byte[0]);
                                    iterator.remove();
                                    file.delete();
                                    bufferedOutputStream.flush();
                                    bufferedOutputStream.close();
                                    fileOutputStream.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            });
        }
    }
//

    private void updateMessageList(String senderId, String avatarPath) {

        if (avatarPath != null) {
            for (Msg msg : msgList) {
                if (msg.getSenderId().equals(senderId)) {
                    msg.setAvatarPath(avatarPath);
                }
            }
        }

        this.adapter = new MsgAdapter(msgList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(OneToOneChatActivity.this);
        msgRecyclerView.setLayoutManager(layoutManager);
        this.msgRecyclerView.setAdapter(adapter);
        adapter.notifyItemInserted(msgList.size() - 1);//当有新消息是刷新RecyclerView中的显示
        msgRecyclerView.scrollToPosition(msgList.size() - 1);//将RecyclerView定位在最后一行
        GlobalRoomBean globalRoomBean = new GlobalRoomBean();
        globalRoomBean.setRoomName(roomName);
        globalRoomBean.setAdapter(adapter);
        globalRoomBean.setMsgList(msgList);
        globalRoomBean.setActivity(OneToOneChatActivity.this);
        globalRoomBean.setMsgRecyclerView(msgRecyclerView);
        GlobalChatRoomMap.putRoomInfo(this.roomName, globalRoomBean);

    }

    @SuppressLint("SetTextI18n")
    public void updateFriendStatus(int status) {

        String onlineStatus = status == 0 ? "离线" : "在线";
        username.setText(friendName + "(" + onlineStatus + ")");

    }
}
